package com.woniuxy.couponassembly.apiimpl;


import com.woniuxy.api.CouponApi;
import com.woniuxy.common.Result;
import com.woniuxy.couponassembly.model.Coupon;
import com.woniuxy.couponassembly.service.ICouponService;
import com.woniuxy.form.CouponForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Liyfi
 * @since 2021-05-31
 */
@RestController
@Slf4j
public class CouponController implements CouponApi {
    @Autowired
    private ICouponService service;

    @Override
    public Result addCoupon(CouponForm form) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp endDate = null;
        Timestamp startDate = null;
        try {
            endDate =new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(form.getEndDate()).getTime());
            startDate =new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(form.getStartDate()).getTime());

        } catch (ParseException e) {
            e.printStackTrace();
        }
        log.info("时间转换:{},{}",endDate,startDate);
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(form,coupon);
        coupon.setDiscount(form.getDiscount()/10);
        coupon.setStartDate(startDate);
        coupon.setEndDate(endDate);
        int i = service.addCoupon(coupon);
        if(i == 1){
            return Result.success("添加成功");
        }
            return Result.fail("添加失败");
    }

    @Override
    public Result getLimitNum(int couponId) {
        int couponId1 = service.getCouponId(couponId);

        return Result.success(couponId1);
    }

    @Override
    public Result getIssuedQuantity(int couponId) {
        int issuedQuantity = service.getIssuedQuantity(couponId);
        return Result.success(issuedQuantity);
    }

    @Override
    public Result isItExpired(int couponId) {
        int i = service.findCoupon(couponId);
        if(i == 1){
            return Result.success("无效");
        }
        return Result.success("有效");
    }


}

